#!/usr/bin/env python3

import sys,os
sys.path.append(os.path.dirname(__file__))


from config import DropboxAPP,DB
from dropbox import client, session
import time

def make_dump_db():
    path=os.path.dirname(__file__)+'/backup/'
    now=time.ctime().split()
    date=now[1]+'_'+now[2]+'.sql'
    filename=path+date
    command='/usr/bin/mysqldump -u%s -p%s %s > %s'  % (DB['user'],DB['passwd'],DB['db'], filename)
    os.system(command)
    Dropboxuploader(filename,dropbox_path='/Web/Bishop/backup/%s' % date)

def Dropboxuploader(local_path,dropbox_path):
    APP_KEY=DropboxAPP['APP_KEY']
    APP_SECRET=DropboxAPP['APP_SECRET']
    ACCESS_TYPE=DropboxAPP['ACCESS_TYPE']
    ACCESS_KEY=DropboxAPP['ACCESS_KEY']
    ACCESS_SECRET=DropboxAPP['ACCESS_SECRET']
    sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
    sess.set_token(ACCESS_KEY, ACCESS_SECRET)
    upload_session = client.DropboxClient(sess)
    filesize=os.path.getsize(local_path)
    try:
        uploader=upload_session.get_chunked_uploader(local_path,filesize)
        while uploader.offset < filesize:
            try:
                upload=uploader.upload_chunked()
            except:
                raise
        uploader.finish(local_path)
    except:
        openfile=open(local_path, 'rb')
        upload_session.put_file(dropbox_path,openfile)
        openfile.close()


make_dump_db()


